package com.alipay.sdk.pay.demo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

public class DemoActivity extends FragmentActivity {

    public static final String PARTNER = "2088611208250175";
    public static final String SELLER = "pay@txigame.com";
    public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALQ/Xnow/qZNx3mW3+t67nI3et4iGS5CUeYO1Zjtmh5RPdiC8O1s/ZMObQorbuuyOfrask7bGfnJ3RDvGGWYdzxKkX+8Y1uUI75NsjrpIkY3Q7U8quy5nk3E59Al0qWIpbkpOq47Fz1SGRl/g9v4/OeaLxFD9eECBXYoPVC8jKjvAgMBAAECgYA0GWj2irjgWvUAaSK6DuNjMjQahuKeY18Gz1zgAjWc88Cbl2WKSwmUewP7f4hlKjPmFVaawmvkrntujJ2RqBs2XuvjRdhHkewLUjeLErvkXrWin/30b5FtKq92EKNVfzvcAM1cTry9iqnnDwFJrKbyoWmSVYktXO9E9L1OxmQYCQJBANjCCvBLe3xqwr21wBvVyYualOVNhGjfnztO9lEvNR2/wUK0AHMtb9lvuSMBg063UYGSuiq5mgY8Zk9zhhhZoY0CQQDU4TKinFKcCDaaQkbZeb6nAv3NzyoaNAr8nybjLKI8omFpH2bQ/oQjPubNWSjI972UcFdhhCJAF11kLxZWsm9rAkEAmCNCKDzitIX+n8ckyqS4bKsYHQXWjQGAMtGOY5cd0f6YOCg9NJpMqjIXoPFb53EV3TtOPdS9vejA6r0r/oVStQJAEMsbJXzTf3+eXxjvYeSax64Su5OmLJ8CZt9fP/iba9EbgiF6CO6rGeSybGymLQRuLjGWkxjLYub09RxJ1NkKtQJAIW4O0vNkd9Yj/6a8W7W67Kj51MkEROTeiA7EwsB9TgYyz4v3+xa5EQN1ke6zXXzNXFeTFfqra8T1/kEuEeLUuQ==";
    public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0P156MP6mTcd5lt/reu5yN3reIhkuQlHmDtWY7ZoeUT3YgvDtbP2TDm0KK27rsjn62rJO2xn5yd0Q7xhlmHc8SpF/vGNblCO+TbI66SJGN0O1PKrsuZ5NxOfQJdKliKW5KTquOxc9UhkZf4Pb+Pznmi8RQ/XhAgV2KD1QvIyo7wIDAQAB";

    private static final int RQF_PAY = 1;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d("DemoActivity", msg.obj.toString());

            Result result = new Result((String) msg.obj);
            switch (msg.what) {
            case RQF_PAY: {
                Toast.makeText(DemoActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
            }
                break;
            default:
                break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_main);

        Log.e("DemoActivity", "----------- onCreate");
    }

    // 支付接口调用
    public void pay(View v) {
        String info = null;
        try {
            String orderInfo = DemoActivity.getOrderInfo("测试商品", "测试商品的详细描述", "0.01");
            String sign = DemoActivity.sign(orderInfo);
            sign = URLEncoder.encode(sign, "UTF-8");
            info = orderInfo + "&sign=" + "\"" + sign + "\"" + "&" + DemoActivity.getSignType();
        } catch (UnsupportedEncodingException e) {}

        final String orderInfo = info;

        new Thread() {
            public void run() {

                PayTask alipay = new PayTask(DemoActivity.this);
                String result = alipay.pay(orderInfo);

                Message msg = new Message();
                msg.what = RQF_PAY;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }.start();
    }

    // 查询本终端是否存在支付宝认证账户
    public void check(View v) {
        PayTask payTask = new PayTask(this);
        boolean isExist = payTask.checkAccountIfExist();
        Toast.makeText(this, "" + isExist, Toast.LENGTH_SHORT).show();
    }

    // 获取SDK 版本号
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
        Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
    }

    public static String getOrderInfo(String subject, String body, String price) {
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";
        orderInfo += "&";
        orderInfo += "seller_id=" + "\"" + SELLER + "\"";
        orderInfo += "&";
        orderInfo += "out_trade_no=" + "\"" + getOutTradeNo() + "\"";
        orderInfo += "&";
        orderInfo += "subject=" + "\"" + subject + "\"";
        orderInfo += "&";
        orderInfo += "body=" + "\"" + body + "\"";
        orderInfo += "&";
        orderInfo += "total_fee=" + "\"" + price + "\"";
        orderInfo += "&";
        orderInfo += "notify_url=" + "\"" + "http://notify.msp.hk/notify.htm" + "\"";

        // 接口名称， 定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型，定值
        orderInfo += "&payment_type=\"1\"";

        // 字符集，默认utf-8
        orderInfo += "&_input_charset=\"utf-8\"";

        // 超时时间 ，默认30分钟.
        // 设置未付款交易的超时时间，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        // 该功能需要联系支付宝配置关闭时间。
        orderInfo += "&it_b_pay=\"30m\"";

        // 商品展示网址,客户端可不加此参数
        orderInfo += "&show_url=\"m.alipay.com\"";

        // orderInfo += "&paymethod=\"expressGateway\"";

        // orderInfo += "&cashier_type=\"quick\"";

        // verify(sign, orderInfo);

        return orderInfo;
    }

    // @SuppressWarnings("deprecation")
    // private static void verify(String sign, String content) {
    // String decodedSign = URLDecoder.decode(sign);
    // boolean isOk = Rsa.doCheck(content, decodedSign, RSA_PUBLIC);
    // System.out.println(isOk);
    // }

    /**
     * get the out_trade_no for an order. 获取外部订单号
     * 
     * @return
     */
    public static String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        java.util.Random r = new java.util.Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    /**
     * sign the order info. 对订单信息进行签名
     * 
     * @param signType
     *            签名方式
     * @param content
     *            待签名订单信息
     * @return
     */
    public static String sign(String content) {
        return Rsa.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     * 
     * @return
     */
    public static String getSignType() {
        return "sign_type=\"RSA\"";
    }
}
